#!/bin/bash

# kmsg-ui 开发环境启动脚本

echo "🚀 启动 kmsg-ui 开发环境"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker"
    exit 1
fi

# 启动基础服务 (Redis, Kafka)
echo "📦 启动基础服务 (Redis, Kafka)..."
docker-compose up -d redis zookeeper kafka

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# 检查服务状态
echo "🔍 检查服务状态..."
docker-compose ps

# 启动后端服务
echo "🐍 启动后端服务..."
cd backend
if [ ! -d "venv" ]; then
    echo "📦 创建Python虚拟环境..."
    python -m venv venv
fi

# 激活虚拟环境
source venv/bin/activate 2>/dev/null || source venv/Scripts/activate

# 安装依赖
echo "📦 安装Python依赖..."
pip install -r requirements.txt

# 启动FastAPI服务
echo "🚀 启动FastAPI服务..."
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 &
BACKEND_PID=$!

cd ..

# 启动前端服务
echo "⚛️ 启动前端服务..."
cd frontend

# 安装依赖
if [ ! -d "node_modules" ]; then
    echo "📦 安装Node.js依赖..."
    npm install
fi

# 启动Vite开发服务器
echo "🚀 启动Vite开发服务器..."
npm run dev &
FRONTEND_PID=$!

cd ..

echo "✅ 开发环境启动完成！"
echo ""
echo "🌐 服务地址:"
echo "  前端应用: http://localhost:3000"
echo "  后端API: http://localhost:8000"
echo "  API文档: http://localhost:8000/docs"
echo "  Kafka UI: http://localhost:8080"
echo ""
echo "📋 服务配置:"
echo "  Redis: localhost:6379 (密码: 123456)"
echo "  Kafka: localhost:9092"
echo ""
echo "🛑 停止服务: Ctrl+C 或运行 scripts/stop-dev.sh"

# 等待用户中断
trap "echo '🛑 停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; docker-compose down; exit 0" INT

wait
